/**
 *
 */
package com.elite.groovy.callback

import cn.com.elite.PropertiesUtil
import com.elite.groovy.util.EliteBean
import com.rabbitmq.client.Channel
import com.rabbitmq.client.Connection
import com.rabbitmq.client.ConnectionFactory
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse //导入grooby的json解析api包

/**
 * @use 定时调度，将符合要求数据送到智能回访中心
 * @author chopper
 *
 */

public class sendRabbitMq implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(sendRabbitMq.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response){
		JSONObject result = new JSONObject();
		log.debug("-----智能回访推送start----------");
		//String bustype=request.getParameter("bustype");
		//log.debug("bustype:"+bustype);
		try {
			getNewOrder(eliteBean)
			result.put("code", "1");
			result.put("msg", "");
			return result;
		}catch(Exception e) {
			log.error("ErrorMessage:",e);
			result.put("code", "-1");
			result.put("msg", "fail");
			return result;
		}
	}
/**
 * @use 推送增值回访消息
 * @return
 * @throws Exception
 */
	private static boolean getNewOrder(EliteBean eliteBean) throws Exception{

		/**
		 * @use 增值回访数据查询和推送信息拼接
		 *
		 */
		log.debug("-----增值 VAS 回访推送start----------");
		def querysql1="select to_char(v.createddate,'yyyy-mm-dd hh24:mi:ss') v_nowdate,v.visittask_guid visittask_guid,v.objective_guid v_objective_guid,t.order_id v_order_id,case when o.callstarttime is not null then to_char(o.callstarttime,'yyyy-mm-dd hh24:mi:ss') else to_char(o.createddate,'yyyy-mm-dd hh24:mi:ss') end v_callstarttime,c.customername v_customername,c.mobile v_mobile,o.calltel v_calltel,o.carno v_carno,t.province_name||t.city_name||t.area_name||t.address v_address,t.item_name v_item_name,t.service_type_name v_service_type_name,t.supplier_name v_supplier_name from OB_VISITTASK v left join objective o on o.objective_guid=v.objective_guid left join tabcdh_vas_list t on t.relation_id=v.objective_guid  left join customer c on c.customer_guid=o.customer_guid where v.MAP_ID in('HWYY20','K3ZK57' )and v.TASKSTATUS=0 and v.BUSTYPE='VAS'  and o.objectivestatus='OPEN'";
		def list1=eliteBean.chaxun_sql(querysql1,"dataSource");
		log.debug("list1-------------------------------"+list1);
		log.debug("list1.size-------------------------------"+list1.size);
		for(def j=0;j<list1.size;j++){

			def map1=list1[j];
			def v_visittask_guid=map1.get("visittask_guid");//数据唯一guid
			log.debug("v_visittask_guid---------------"+v_visittask_guid);
			JSONObject json = new JSONObject();
			json.put("ID", map1.get("visittask_guid")  ==null?"":(String)map1.get("visittask_guid"));
			json.put("OrderId", map1.get("v_order_id")  ==null?"":(String)map1.get("v_order_id"));
			json.put("CallTime", map1.get("v_callstarttime")  ==null?"":(String)map1.get("v_callstarttime"));
			json.put("CallName", map1.get("v_customername")  ==null?"":(String)map1.get("v_customername"));
			json.put("CallTel", map1.get("v_mobile")  ==null?"":(String)map1.get("v_mobile"));
			json.put("CallPhone", map1.get("v_calltel")  ==null?"":(String)map1.get("v_calltel"));
			json.put("LicenseNo", map1.get("v_carno")  ==null?"":(String)map1.get("v_carno"));
			json.put("Address", map1.get("v_address")  ==null?"":(String)map1.get("v_address"));
			json.put("Item", map1.get("v_item_name")  ==null?"":(String)map1.get("v_item_name"));
			json.put("ServiceType", map1.get("v_service_type_name")  ==null?"":(String)map1.get("v_service_type_name"));
			json.put("Supplier", map1.get("v_supplier_name")  ==null?"":(String)map1.get("v_supplier_name"));
			json.put("SignTime", map1.get("v_nowdate")  ==null?"":(String)map1.get("v_nowdate"));
			log.debug("增值推送报文------------------------"+json);
			sendMsg("KF_VAS_VISIT","DH_VAS_VISIT",json.toString());

			/**
			 * @use 增值回访已推送更新结果
			 *
			 */
			log.debug("-----增值 VAS 回访完成更新接口表----------");
			def updatesql1="update OB_VISITTASK v set TASKSTATUS=1,sendtime=sysdate where  v.TASKSTATUS=0 and v.BUSTYPE='VAS' and v.visittask_guid='"+v_visittask_guid+"'";
			def updatesqlresult1=eliteBean.update(updatesql1,"dataSource");
			log.debug("updatesqlresult1:"+updatesqlresult1);

		}

		/**
		 * @use 报案回访数据查询和推送信息拼接
		 *
		 */
		log.debug("-----报案 REPORT 回访推送start----------");
		def querysql2="select distinct to_char(v.createddate,'yyyy-mm-dd hh24:mi:ss') v_nowdate, v.visittask_guid visittask_guid,r.policy_no v_policy_no,v.businessno v_businessno,r.license_no v_license_no,r.insured_name v_insured_name,r.reportor_name v_reportor_name,r.reportor_phone v_reportor_phone,r.linker_name v_linker_name,r.linker_phone v_linker_phone,to_date(r.report_time,'yyyy-mm-dd hh24:mi:ss') v_report_time,r.accident_course v_accident_course,to_date(r.happened_time,'yyyy-mm-dd hh24:mi:ss') v_happened_time,r.examine_address v_examine_address,r.firstsiteflag v_firstsiteflag,r.damagecode v_damagecode,r.subcertitype v_subcertitype,r.self_claim_flag v_self_claim_flag,dh.is_self v_IsSelf,rg.rolegroupdescription v_departname from Ob_visitTask v left join DH_REPORT r on r.CLM_NO=v.businessno left join dh_report_dispatch dh on dh.REPORT_ID=r.clm_no left join rolegroup rg on rg.org_id=(case when substr(r.policy_no,2,2)='00' then substr(r.policy_no,2,2)||'020000' when substr(r.policy_no,2,2)!='00'	then substr(r.policy_no,2,2)||'000000' end)	 where v.TASKSTATUS=0 and BUSTYPE='REPORT'";
		def list2=eliteBean.chaxun_sql(querysql2,"dataSource");
		log.debug("list2-------------------------------"+list2);
		for(def k=0;k<list2.size;k++){
			def map2=list2[k];
			def v_visittask_guid=map2.get("visittask_guid");//数据唯一guid
			log.debug("v_visittask_guid---------------"+v_visittask_guid);

			JSONObject json = new JSONObject();
			json.put("ID", map2.get("visittask_guid")  ==null?"":(String)map2.get("visittask_guid"));
			json.put("PolicyNo", map2.get("v_policy_no")  ==null?"":(String)map2.get("v_policy_no"));
			json.put("ClmNo", map2.get("v_businessno")  ==null?"":(String)map2.get("v_businessno"));
			json.put("LicenseNo", map2.get("v_license_no")  ==null?"":(String)map2.get("v_license_no"));
			json.put("InsuredName", map2.get("v_insured_name")  ==null?"":(String)map2.get("v_insured_name"));
			json.put("ReporterName", map2.get("v_reportor_name")  ==null?"":(String)map2.get("v_reportor_name"));
			json.put("ReporterPhone", map2.get("v_reportor_phone")  ==null?"":(String)map2.get("v_reportor_phone"));
			json.put("LinkerName", map2.get("v_linker_name")  ==null?"":(String)map2.get("v_linker_name"));
			json.put("LinkerPhone", map2.get("v_linker_phone")  ==null?"":(String)map2.get("v_linker_phone"));
			json.put("ReportTime", map2.get("v_report_time")  ==null?"":(String)map2.get("v_report_time"));
			json.put("AccidentCourse", map2.get("v_accident_course")  ==null?"":(String)map2.get("v_accident_course"));
			json.put("DamageTime", map2.get("v_happened_time")  ==null?"":(String)map2.get("v_happened_time"));
			json.put("ExamineAddress", map2.get("v_examine_address")  ==null?"":(String)map2.get("v_examine_address"));
			json.put("FirstSiteFlag", map2.get("v_firstsiteflag")  ==null?"":(String)map2.get("v_firstsiteflag"));
			json.put("DamageCode", map2.get("v_damagecode")  ==null?"":(String)map2.get("v_damagecode"));
			json.put("SubCertiType", map2.get("v_subcertitype")  ==null?"":(String)map2.get("v_subcertitype"));
			json.put("SelfClaimFlag", map2.get("v_self_claim_flag")  ==null?"":(String)map2.get("v_self_claim_flag"));
			json.put("IsSelf", map2.get("v_IsSelf")  ==null?"":(String)map2.get("v_IsSelf"));
			json.put("SignTime", map2.get("v_nowdate")  ==null?"":(String)map2.get("v_nowdate"));
			json.put("DepartName",map2.get("v_departname")==null?"":(String)map2.get("v_departname"))
			log.debug("报案推送报文------------------------"+json);
			sendMsg("KF_REPORTNEW_VISIT","DH_REPORTNEW_VISIT",json.toString());

			/**
			 * @use 报案回访已推送更新结果
			 *
			 */
			log.debug("-----报案 REPORT 回访推送完成更新接口表----------");
			def updatesql2="update Ob_visitTask set TASKSTATUS=1,sendtime=sysdate where TASKSTATUS=0 and BUSTYPE='REPORT' and VISITTASK_GUID='"+v_visittask_guid+"'";
			def updatesqlresult2=eliteBean.update(updatesql2,"dataSource");
			log.debug("updatesqlresult2:"+updatesqlresult2);


		}

		/**
		 * @use 临时回访数据查询和推送信息拼接--借用不满意回访
		 *
		 */
		log.debug("-----临时回访推送start----------");
		def querysql3="select  relation_id id ,'6999' serviceagent,'满意' serviceevluate ,CONTACT custname,contact_mobile ani,'2024-08-02 12:00:00' evaluatetime ,ts_customertype custtype, loss_type opertypename,'100' reportno,to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') signtime from tabcdh_ts_order where loss_type ='十不要抽检' and ts_source = '0' ";
		def list3=eliteBean.chaxun_sql(querysql3,"dataSource");
		log.debug("list3-------------------------------"+list3);
		for(def i=0;i<list3.size;i++){
			def map3=list3[i];
			def relation_id=map3.get("id");//数据唯一guid
			JSONObject json = new JSONObject();
			json.put("ID", map3.get("id")  ==null?"":(String)map3.get("id"));
			json.put("ServiceAgent", map3.get("serviceagent")  ==null?"":(String)map3.get("serviceagent"));
			json.put("ServiceEvaluate", map3.get("custname")  ==null?"":(String)map3.get("custname"));
			json.put("CustName", map3.get("v_license_no")  ==null?"":(String)map3.get("v_license_no"));
			json.put("Ani", map3.get("ani")  ==null?"":(String)map3.get("ani"));
			json.put("EvaluateTime", map3.get("evaluatetime")  ==null?"":(String)map3.get("evaluatetime"));
			json.put("CustType", map3.get("custtype")  ==null?"":(String)map3.get("custtype"));
			json.put("OperTypeName", map3.get("opertypename")  ==null?"":(String)map3.get("opertypename"));
			json.put("ReportNo", map3.get("reportno")  ==null?"":(String)map3.get("reportno"));
			json.put("SignTime", map3.get("signtime")  ==null?"":(String)map3.get("signtime"));
			log.debug("临时回访推送报文------------------------"+json);
			sendMsg("KF_NOSATI_VISIT","DH_NOSATI_VISIT",json.toString());

			/**
			 * @use 报案回访已推送更新结果
			 *
			 */
			log.debug("-----临时回访 回访推送完成更新接口表----------");
			def updatesql3="update tabcdh_ts_order set ts_source='1',HANDLE_TIME=sysdate where ts_source='0' and relation_id='"+relation_id+"'";
			def updatesqlresult3=eliteBean.update(updatesql3,"dataSource");
			log.debug("updatesqlresult3:"+updatesqlresult3);


		}


	}
	/**
	 * @use RabbitMq发送队列消息
	 * @param exchangename
	 * @param routingkey
	 * @param msg
	 * @return
	 * @throws Exception
	 */
	private static boolean sendMsg(String exchangename,String routingkey,String msg) throws Exception{
		log.debug("===================发送RabbitMq消息=====================");
		// 获取到连接以及mq通道
		Connection connection = getConnection();
		// 从连接中创建通道
		Channel channel = connection.createChannel();
		// 声明exchange
		channel.exchangeDeclare(exchangename, "topic",true);
		channel.queueDeclare(routingkey, false, false, false, null);
		// 绑定队列到交换机，并设置路由键
		channel.queueBind(routingkey,exchangename,routingkey);
		def ret = channel.basicPublish(exchangename, routingkey, null, msg.getBytes("UTF-8"));
		log.debug("MQ发送结果"+routingkey+":"+ret);
		//关闭通道和连接
		channel.close();
		connection.close();
		return true
	}


	/**
	 * @use RabbitMq创建连接
	 * @return
	 * @throws Exception
	 */
	private static Connection getConnection() throws Exception {
		String string = new String("中".getBytes("UTF-8"),"GBK");
		PropertiesUtil p = new PropertiesUtil();
		String host =p.readValue("MQhost");
		int port = 5672;
		String vhost = p.readValue("MQvirtualhost");
		String username = p.readValue("MQuserName");
		String password = p.readValue("MQpassword");
		log.debug("host:"+host+"|vhost:"+vhost+"|username:"+username+"|password:"+password);
		//定义连接工厂
		ConnectionFactory factory = new ConnectionFactory();
		//设置服务地址
		factory.setHost(host);
		//端口
		factory.setPort(port);
		//设置账号信息，用户名、密码、vhost
		factory.setVirtualHost(vhost);
		factory.setUsername(username);
		factory.setPassword(password);
		// 通过工程获取连接
		Connection connection = factory.newConnection();
		return connection;
	}

}
